/*
 * @Author: 郝奔 1425466221@qq.com
 * @Date: 2024-12-05 16:01:34
 * @LastEditors: 郝奔 1425466221@qq.com
 * @LastEditTime: 2025-01-06 11:02:36
 * @FilePath: /HG-dqbasic_open_platform/src/framework/store/modules/user.ts
 * @Description: 
 * Copyright (c) 2024-present HBIS Digital Technology Co.,Ltd. All rights reserved. 
 */

import { defineStore } from 'pinia';

import { getToken, setToken, removeToken } from '@/framework/utils/auth';
import { loginApi, logoutApi, isAuth } from '@/framework/api/auth';
import { getUserInfo, loginBySms } from '@/framework/api/user';
import { resetRouter } from '@/router';
import { store } from '@/store';

import { ref } from 'vue';
import { UserInfo } from '@/framework/api/user/types';
import { encryption, decryption } from '@/framework/utils/cryptojs/index.js'
import { localStorage } from '@/framework/utils/localStorage';
import { ResultData } from '@/framework/api/common';
import { simpleUserInfoLoginRes, LoginData } from '@/framework/api/auth/types';
import { useWebsocketStore } from './websocket';
import { useSettingsStore } from '@/framework/store/modules/settings';
type UserStoreType = ReturnType<typeof useUserStore>;
export const useUserStore = defineStore('user', () => {
  const settingsStore = useSettingsStore();
  const hasMessage = computed(() => settingsStore.hasMessage)
  // state
  const token = ref<string>(getToken() || '');
  const nickname = ref<string>('');
  const avatar = ref<string>('');
  const userId = ref<string>('')
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const perms = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限
  const realName = ref<string>('');
  const organizationId = ref<string>('');
  const authorities = ref<Array<string>>([]);
  const wsUrl = ref<string>('');
  const isLock = ref<boolean>(false);
  const passWordConfig = ref({
    pwdBeAboutExpired: false,
    pwdExpiredDays: 0,
    pwdExpiredTime: ''
  });

  const websocketStore = useWebsocketStore()
  // actions

  // 登录
  function login(loginData: LoginData): Promise<void> {
    const password = encryption<LoginData>({
      data: loginData
    })
    return new Promise<void>((resolve) => {
      loginApi(password)
        .then(response => {
          const res = decryption<ResultData<simpleUserInfoLoginRes>>(response)
          token.value = res.data.token;
          setToken(res.data.token);
          console.log(112)
          setPasswordConfig(res.data)
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  }
  function setUserToken(userToken: string): void {
    token.value = userToken
  }
  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getInfo(): Promise<UserInfo> {
    return new Promise((resolve, reject) => {
      getUserInfo(token.value)
        .then(({ data }) => {
          if (!data) {
            return reject('验证失败，请重新登录');
          }

          if (!data.roles || data.roles.length <= 0) {
            reject('getUserInfo: roles must be a non-null array!');
          }
          nickname.value = data.nickname;
          avatar.value = data.avatar;
          roles.value = data.roles;
          perms.value = data.authorities;
          realName.value = data.realName
          organizationId.value = data.organizationId
          authorities.value = data.authorities
          wsUrl.value = data.wsUrl;
          userId.value = data.userId;
          if (hasMessage.value) {
            try {
              websocketStore.WEBSOCKET_INIT(wsUrl.value)
            } catch (error) { }
          }
          // websocketStore.WEBSOCKET_INIT(wsUrl.value)

          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  function microappUserInfo(data:UserInfo):void{
    nickname.value = data.nickname;
    avatar.value = data.avatar;
    roles.value = data.roles;
    perms.value = data.authorities;
    realName.value = data.realName
    organizationId.value = data.organizationId
    authorities.value = data.authorities
    wsUrl.value = data.wsUrl;
    userId.value = data.userId;
  }

  // 注销
  function logout(): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      logoutApi()
        .then(() => {
          resetRouter();
          resetToken();
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  function setLock(state: boolean): void {
    isLock.value = true
    localStorage.set('isLock', state)
  }
  function clearLock(): void {
    isLock.value = false
    localStorage.remove('isLock')
  }
  function setPasswordConfig(passWordConfigData: simpleUserInfoLoginRes): void {
    passWordConfig.value = passWordConfigData
  }

  // 短信登录
  function smslogin(smsLoginData: string): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      loginBySms(smsLoginData).then((res) => {
        const response = decryption<ResultData<simpleUserInfoLoginRes>>(res)
        token.value = response.data.token;
        setToken(response.data.token)
        resolve();
      }).catch((error) => {
        reject(error)
      })
    })
  }

  // 重置
  function resetToken(): void {
    removeToken();
    token.value = '';
    nickname.value = '';
    avatar.value = '';
    roles.value = [];
    perms.value = [];
    realName.value = '';
    organizationId.value = '';
    authorities.value = [];
    wsUrl.value = '';
    isLock.value = false;
    passWordConfig.value = {
      pwdBeAboutExpired: false,
      pwdExpiredDays: 0,
      pwdExpiredTime: ''
    },
      userId.value = '';
  }
  /**
   * @description: 是否鉴权
   * @return {*}
   */
  function getLicense(): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      isAuth().then((res) => {
        resolve(res)
      })
    })
  }
  return {
    token,
    nickname,
    avatar,
    roles,
    perms,
    login,
    getInfo,
    logout,
    resetToken,
    realName,
    organizationId,
    authorities,
    wsUrl,
    isLock,
    setLock,
    clearLock,
    passWordConfig,
    smslogin,
    setUserToken,
    userId,
    getLicense,
    microappUserInfo
  };
});

// 非setup
export function useUserStoreHook(): UserStoreType {
  return useUserStore(store);
}
